package com.delianna.bwt.data;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.util.Log;

import com.delianna.bwt.models.BWT;

/**
 * @author Delio Castillo (jangeador@gmail.com)
 * 
 */
public class XmlParser extends Activity {

	private static final String defaultURL = "http://apps.cbp.gov/bwt/bwt.xml";

	public static BWT Parse(boolean isOnline) {
		return Parse(defaultURL, false, isOnline);
	}

	public static BWT Parse(boolean forceDownloadFromWeb, boolean isOnline) {
		return Parse(defaultURL, forceDownloadFromWeb, isOnline);
	}

	public static BWT Parse(String stringURL, boolean forceDownloadFromWeb,
			boolean isOnline) {
		BWT bwt = null;

		// sax stuff
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();

			XMLReader xr = sp.getXMLReader();

			DataHandler dataHandler = new DataHandler();
			xr.setContentHandler(dataHandler);

			if (forceDownloadFromWeb && isOnline) {
				Cache.saveCacheFileFromURL(defaultURL, "bwt.xml");
			}
			// Read file from cache or download it from the web
			File content = Cache.getCacheFile("bwt.xml");

			if (content == null && isOnline) {
				Cache.saveCacheFileFromURL(defaultURL, "bwt.xml");
				// try to read from cache now:
				content = Cache.getCacheFile("bwt.xml");
				// still not in cache so let's download from URL
				if (content == null) {
					xr.parse(defaultURL);
				} else {
					xr.parse(convertToFileURL(content));
				}
				bwt = dataHandler.getData();

			} else if (content == null && !isOnline) {
				bwt = null;
			} else {
				// File lives on the cache, use the content string instead.
				xr.parse(convertToFileURL(content));
				bwt = dataHandler.getData();
			}
		} catch (ParserConfigurationException pce) {
			Cache.clearCache();
			Log.e("SAX XML", "sax parse error", pce);
		} catch (SAXException se) {
			Cache.clearCache();
			Log.e("SAX XML", "sax error", se);
		} catch (IOException ioe) {
			Cache.clearCache();
			Log.e("SAX XML", "sax parse io error", ioe);
		}
		return bwt;
	}

	private static String convertToFileURL(File fileUri) {
		String path = fileUri.getAbsolutePath();
		if (!fileUri.exists())
			return null;
		if (File.separatorChar != '/') {
			path = path.replace(File.separatorChar, '/');
		}
		if (!path.startsWith("/")) {
			path = "/" + path;
		}

		return "file:" + path;
	}

	/*
	 * private static Date getLastModifiedDate(File fileUri) {
	
		Date lastModDate = new Date(fileUri.lastModified());
		return lastModDate;
	}
	 */
}
